package org.jeecg.modules.meter.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.basedata.BaseCustomer;
import org.jeecg.entity.basedata.BaseProject;
import org.jeecg.entity.basedata.BaseTenant;
import org.jeecg.entity.charge.ChargeBills;
import org.jeecg.entity.charge.ChargeFeeRule;
import org.jeecg.entity.charge.ChargeFeeitem;
import org.jeecg.entity.charge.ChargeStandard;
import org.jeecg.entity.meter.MeterHandRead;
import org.jeecg.modules.meter.mapper.MeterHandReadMapper;
import org.jeecg.modules.meter.service.IMeterHandReadService;
import org.jeecg.service.IFeignChargeService;
import org.jeecg.vo.basedata.BaseRoomMeterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 手抄表
 * @Author: jeecg-boot
 * @Date:   2021-01-17
 * @Version: V1.0
 */
@Service
public class MeterHandReadServiceImpl extends ServiceImpl<MeterHandReadMapper, MeterHandRead> implements IMeterHandReadService {
    @Autowired
    private MeterHandReadMapper meterHandReadMapper;
    @Autowired
    private IFeignChargeService feignChargeService;


    @Override
    public List<ChargeFeeitem> queryFeeList() {
        return meterHandReadMapper.queryFeeList();
    }

    @Override
    public List<MeterHandRead> findPage(Page<MeterHandRead> page, BaseRoomMeterVo room) {
        List<MeterHandRead> list = meterHandReadMapper.findPage(page, room);
        for (MeterHandRead meterHandRead:list){
            if (1 == meterHandRead.getHasNext()){
                meterHandRead.setNewRead("已录入之后月份的读数");
            }
            if (meterHandRead.getPreRead() == null ){
                String lastRead = meterHandReadMapper.getLastRead(meterHandRead);
                if (null == lastRead){
                    meterHandRead.setPreRead("0");
                }else {
                    meterHandRead.setPreRead(lastRead);
                }
            }
        }
        return list;
     }

    @Override
    public List<BaseProject> queryProjectList(String parentId) {
        return meterHandReadMapper.queryProjectList(parentId);
    }

    @Override
    public ChargeFeeRule queryChargeRule(String feeId, String roomId) {
        return meterHandReadMapper.queryChargeRule(feeId,roomId);
    }

    @Override
    public MeterHandRead queryChargeLastRead(String feeId,String roomId) {
        return meterHandReadMapper.queryChargeLastRead(feeId,roomId);
    }

    @Override
    public BaseCustomer queryCustomerInfo(String roomId) {
        return meterHandReadMapper.queryCustomerInfo(roomId);
    }

    @Override
    public BaseTenant queryTenantInfo(String roomId) {
        return meterHandReadMapper.queryTenantInfo(roomId);
    }


    @Override
    public List<ChargeFeeitem> queryFeeItemByCode(String feeCode,String feeCodeName) {
        return meterHandReadMapper.queryFeeItemByCode(feeCode,feeCodeName);
    }

    @Override
    public ChargeFeeitem queryChargeFeeItemByCodeAndName(String feeCodeName, String feeCode) {
        return meterHandReadMapper.queryChargeFeeItemByCodeAndName(feeCodeName,feeCode);
    }

    @Override
    public void updateBillsStatus(String id) {
        meterHandReadMapper.updateBillsStatus(id);
    }

    @Override
    public List<MeterHandRead> handHistoryRead(String id,String feeId) {
        return meterHandReadMapper.handHistoryRead(id,feeId);
    }

    @Override
    public List<MeterHandRead> allRead(Page<MeterHandRead> page, BaseRoomMeterVo baseRoomMeterVo) {
        return meterHandReadMapper.allRead(page,baseRoomMeterVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveBatchBills(List<String> idList) {
        StringBuilder sb = new StringBuilder();
        int success = 0;
        List<MeterHandRead> meterHandReadList = meterHandReadMapper.findMeterHandRead(idList);
        ArrayList<ChargeBills> chargeBillsList = Lists.newArrayList();
        LoginUser user = SsoUtil.getLoginUser();
        for (MeterHandRead meterHandRead:meterHandReadList){
            ChargeBills chargeBills = new ChargeBills();
            BaseCustomer baseCustomer = meterHandReadMapper.queryCustomerInfo(meterHandRead.getRoomId());
            if (baseCustomer != null){
                chargeBills.setCustomerId(baseCustomer.getId());
                chargeBills.setFloorId(baseCustomer.getFloorId());
            }
            BaseTenant baseTenant =  meterHandReadMapper.queryTenantInfo(meterHandRead.getRoomId());
            if (baseTenant != null){
                chargeBills.setRentId(baseTenant.getId());
                chargeBills.setFloorId(baseTenant.getFloorId());
            }
            if (StringUtils.isBlank(chargeBills.getRentId()) && StringUtils.isBlank(chargeBills.getCustomerId())){
                sb.append(meterHandRead.getRoomId()+"房间无业主或租户,账单生成失败！");
                continue;
            }
            chargeBills.setProjectId(meterHandRead.getProjectId());
            chargeBills.setRoomId(meterHandRead.getRoomId());
            chargeBills.setZjCny(meterHandRead.getReadMonth());
            chargeBills.setDue(meterHandRead.getAmount());
            chargeBills.setThisReading(Double.parseDouble(meterHandRead.getNewRead()));
            chargeBills.setLastReading(Double.parseDouble(meterHandRead.getPreRead()));
            chargeBills.setUnitPrice(meterHandRead.getPrice().doubleValue());
            chargeBills.setElapsedNum(meterHandRead.getUsed().doubleValue());
            chargeBills.setFeePrice(Double.valueOf(meterHandRead.getPrice().toString()));
            chargeBills.setFeeitemId(meterHandRead.getFeeId());
            chargeBills.setDateRange(meterHandRead.getCoverDate());
            chargeBills.setBillsExp(meterHandRead.getCoverDate());
            chargeBills.setTableId(meterHandRead.getId());
            chargeBills.setCreateBy(user.getId());
            chargeBills.setCreateTime(new Date());
            chargeBills.setUpdateBy(user.getId());
            chargeBills.setUpdateTime(new Date());
            ChargeFeeRule chargeFeeRule = queryChargeRule(meterHandRead.getFeeId(),meterHandRead.getRoomId()); //查询收费
            chargeBills.setFeeType(chargeFeeRule.getComputingType().toString());
            chargeBillsList.add(chargeBills);
            success++;
         }
        try {
            String contracts = JSONObject.toJSONString(chargeBillsList);
            boolean res = feignChargeService.saveChargeBillsBatch(contracts, user.getTenantId());
            if (res){
                meterHandReadMapper.updateBatch(idList);//更新账单状态
                return "成功生成账单"+success+"条"+ sb.toString();
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return "系统繁忙,生成失败!";
        }
        return "生成失败!";
    }

    @Override
    public Integer rollBackBillsStatus(String handId) {
        return meterHandReadMapper.rollBackBillsStatus(handId);
    }

    @Override
    public List<MeterHandRead> queryAllRoomHandList(Page<MeterHandRead> page, String roomId) {
        return meterHandReadMapper.queryAllRoomHandList(page,roomId);
    }

}
